package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.additional.query.impl.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.threadlocal.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {


    @Autowired
    FileStorageService fileStorageService;

    @Value("${file.oss.profix}")
    String profix;

    @Value("${file.oss.endpoint}")
    String endpoint;

    @Value("${file.oss.web-site}")
    String webSite;

    /**
     * 上传图片接口
     *
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        // 1 .校验参数
        if (multipartFile == null || multipartFile.getSize() == 0) {

            throw new CustomException(AppHttpCodeEnum.FILE_IS_EMPTY);
        }


        //上传到oss

        String filename = null;

        InputStream inputStream = null;
        try {
            String uuid = UUID.randomUUID().toString().replace("-", "");
            String originalFilename = multipartFile.getOriginalFilename();
            String last = originalFilename.substring(originalFilename.lastIndexOf("."));
            inputStream = multipartFile.getInputStream();
            filename = fileStorageService.store(profix, uuid+last, inputStream);


        } catch (IOException e) {
            e.printStackTrace();
        }




        //保存到数据库中
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setCreatedTime(new Date());
        wmMaterial.setIsCollection((short) 0);
        wmMaterial.setType((short) 0);
        //设置文件id
        wmMaterial.setUrl(filename);

        //当前线程中获取用户id
        WmUser user = WmThreadLocalUtils.getUser();
        if(user==null){
            throw new CustomException(AppHttpCodeEnum.FILE_IS_EMPTY);
        }
        Integer id = user.getId();
        wmMaterial.setUserId(id);
        save(wmMaterial);
        //前端显示

        wmMaterial.setUrl(webSite+filename);

        //返回结果
        return ResponseResult.okResult(wmMaterial);


    }

    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        //校验参数
        dto.checkParam();
        //构建查询条件
        LambdaQueryWrapper<WmMaterial> query = new LambdaQueryWrapper<>();
        //查询收藏
        if(dto.getIsCollection()!=null&&dto.getIsCollection()==1){
            query.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
        //查询所有素材
        WmUser user = WmThreadLocalUtils.getUser();
        if(user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        IPage<WmMaterial> pageParam = new Page<>(dto.getPage(),dto.getSize());
        query.eq(WmMaterial::getUserId,user.getId());

        //按创建时间倒序显示
        query.orderByDesc(WmMaterial::getCreatedTime);
        IPage<WmMaterial> pageResult = page(pageParam, query);

        //处理图片

        List<WmMaterial> wmMaterials = pageResult.getRecords();
        for (WmMaterial wmMaterial : wmMaterials) {
            wmMaterial.setUrl(webSite+wmMaterial.getUrl());
        }

        return new PageResponseResult(dto.getPage(),dto.getSize(),pageResult.getTotal(),pageResult.getRecords());



    }
    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;
    @Override
    public ResponseResult delPicture(Integer id) {


        if(id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //先查wmmaterial表,是否有素材
        WmMaterial wmMaterial1 = getById(id);
        if(wmMaterial1==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //有素材的话,根据查询条件查wmnewsmaterial是否被引用
        LambdaQueryWrapper<WmNewsMaterial> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmNewsMaterial::getMaterialId,id);

        Integer count = wmNewsMaterialMapper.selectCount(queryWrapper);
        if(count>0){
            throw new CustomException(AppHttpCodeEnum.FILE_IS_EMPTY);
        }

        //删除oss图片
        fileStorageService.delete(wmMaterial1.getUrl());
        //删除素材库
        removeById(id);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult updateStatus(Integer id, Short type) {
        //检查参数
        if(id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //更新状态
        //获取当前用户信息



        Integer userId = WmThreadLocalUtils.getUser().getId();
        update(Wrappers.<WmMaterial>lambdaUpdate()
                .set(WmMaterial::getIsCollection,type)
                .eq(WmMaterial::getUserId,userId)
                .eq(WmMaterial::getId,id)
        );
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

    }
}
